<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:前端基类控制器
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app;

use support\Request;
use support\View;
use think\facade\Cache;
use think\facade\Db;

/**
 * 控制器基础类
 * @author [叶华] <[<conqweal@qq.com>]>
 */
abstract class FrontController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * language id
     * @var [type]
     */
    protected $lang_id;

    /**
     * 前端oss存储路径
     * @var string
     */
 
    protected $assign_arr = array();

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct()
    {
        $request = request();

        $this->request = $request;

        $this->assign_arr = array('top_tab'=>1,"osslink" =>'http://localhost:8787/', "version" => 'version=4.2');


       $this->lang_id = getLangs(session("lang", 'zh_CN'));
        

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize()
    {
       
        View::assign('seo', $this->fetchSeo());
    }

    /**
     * seo处理
     * @return [type] [description]
     */
    private function fetchSeo()
    {
        $url = $this->request->path();

        switch ($url) {
            case strpos($url, "/index/Artical/articallist") !== false && $this->request->get("catid"):
                $f = Db::name("cat_description")->where("cat_id", $this->request->get("catid"))->where("language_id", $this->lang_id)->cache(true)->json(["seo"])->value("seo");
                break;

            case strpos($url, "/index/Artical/getartical") !== false && $this->request->get("id"):
                $f = Db::name("info_description")->where("info_id", $this->request->get("id"))->where("language_id", $this->lang_id)->cache(true)->json(["seo"])->value("seo");

                break;
            case strpos($url, "/index/Index/tasklist") !== false && $this->request->get("id"):
                $f = Db::name("cat_description")->where("cat_id", $this->request->get("id"))->where("language_id", $this->lang_id)->cache(true)->json(["seo"])->value("seo");
                break;

            case strpos($url, "/index/Task/taskdetail") !== false && $this->request->get("taskid"):
                $f = Db::name("mission_description")->where("mission_id", $this->request->get("taskid"))->where("language_id", $this->lang_id)->cache(true)->json(["seo"])->value("seo");
                break;

            default:
                $f = Db::name("seo")->alias("a")->join("seo_description b", "a.id=b.id  and b.language_id=" . $this->lang_id)->cache(true)->where('a.url', $url)->json(['b.seo'])->value("seo");
                break;
        }

        if (!$f) {
            $f = Db::name("seo")->alias("a")->join("seo_description b", "a.id=b.id  and b.language_id=" . $this->lang_id)->cache(true)->where('a.url', '/index/Index/index')->json(['b.seo'])->value("seo");

        }

      
        $seo = is_array($f)?$f:json_decode($f,true);
        return $seo;
    }

    //
    // 以下为新增，为了使用旧版的 success error redirect 跳转  start
    //

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : app('route')->buildUrl($url);
        }

        $result = [
            'code' => 1,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];

        $type = $this->getResponseType();
        if ($type == 'html') {
            $response = view('index/view/dispatch', $result);
        } else if ($type == 'json') {
            $response = json($result);
        }
        return response($response);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url)) {
            $url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);';
        }

        $result = [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];

        $type = $this->getResponseType();
        if ($type == 'html') {
            $response = view('index/view/dispatch', $result);
        } else if ($type == 'json') {
            $response = json($result);
        }
        return response($response);
    }

    /**
     * URL重定向  自带重定向无效
     * @access protected
     * @param  string         $url 跳转的URL表达式
     * @param  array|integer  $params 其它URL参数
     * @param  integer        $code http code
     * @param  array          $with 隐式传参
     * @return void
     */
    protected function redirect($url, $code = 302, $headers = [])
    {

        $response = new Response($code, ['Location' => $url]);
        if (!empty($headers)) {
            $response->withHeaders($headers);
        }
        return $response;
    }

    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected function getResponseType()
    {
        return $this->request->isAjax() ? 'json' : 'html';
    }

    /**
     * 方法不存在处理
     * @param  [type] $name      [description]
     * @param  [type] $arguments [description]
     * @return [type]            [description]
     */
    public function __call($name, $arguments)
    {

        $result = [
            'status'  => 0,
            'message' => '找不到该方法',
            'result'  => null,
        ];
        return json($result, 400);
    }

}
